<?php

namespace Home\Controller;
use Think\Controller;
class CommonController extends Controller{
	//用户ID
	public $user_id            = 0;
	//用户头像
	public $user_head_url      = '';
	//用户手机号
	public $user_mobile        = '';
	//用户E-mail
	public $user_email         = '';
	//用户昵称
	public $user_nickname      = '';
	// 用户客服ID
	public $user_service_id    = '';
	//设置密码
	public $set_password       = '';
	//用户城市ID
	public $user_city_id       = 0;
	// 邮箱是否认证
	public $is_auth_email      = 0;
	//用户积分
	public $user_score         = 0;
	public $pagesize           = 10;
	// 显示头部导航
	public $is_show_header_nav = 1;
	//接口SDK
	public $api;
	//H5头部标题
	public $top_title;
	private $_trail            = array ();//导航数据
	private $_title            = null;//当前页面标题
	public $_cur_title         = null;//当前标题

	//该函数相当于__Construct()函数
	public function _initialize(){
		// 手机访问登录WAP网站
		if(preg_match("/(Android|windows phone|iPhone|iPad|iPod|iOS)/si", $_SERVER['HTTP_USER_AGENT'])){
			// 默认跳转地址
			$url = 'http://m.milv.cn';// 正式
			// $url = 'http://m.milv.com';// 测试
			// 知识库文章跳转地址
			if(CONTROLLER_NAME == 'Knowledge'){
				$url = $url . "/article/detail.html/?article_id=" . $this->_get('article_id');
				// $url = '';// 不跳转
				// var_dump($url);exit;
			}
			if($url){
            	redirect($url);
			}
        }
        // 用户信息
		$this->user_id(false);

		$this->assign('left_menu_list', $this->get_user_menu_left());

		// 系统配置
		$this->assign('system_config', D('Config')->get('', 'system'));
	}
	//操作步骤
	protected function add_step($title,$url = ''){
		$this->_title     = empty($this->_title) ? $title : $title.' - '.$this->_title;
		$this->_trail[]   = array('title'=>$title,'url'=>$url);
		$this->_cur_title = $title;
		return $this;
	}
	//重写页面显示
	protected function display($templateFile='',$charset='',$contentType='text/html'){
		$this->assign('_title',$this->_title);
		$this->assign('_trail',$this->_trail);
		$this->assign('top_title', $this->top_title ? $this->top_title : $this->_title);
		$this->assign('_cur_title', $this->_cur_title);
		// 是否显示头部导航
		$this->assign('is_show_header_nav', $this->is_show_header_nav);
		parent::display($templateFile,$charset,$contentType);exit();
	}
	/**
	 * 重写成功操作
	 * @param  [type] $info 提示信息
	 * @param  string $url  跳转URL
	 * @param  array  $data 数据
	 */
	protected function success($info, $url = '', $data = array()){
		$json = '';
		if($data || IS_AJAX){
			$json['data'] = $data;
		}
		parent::success($info, $url, $json);
	}
	/**
	 * 重写失败操作
	 * @param  [type] $info 提示信息
	 * @param  string $url  跳转URL
	 * @param  array  $data 数据
	 */
	protected function error($info, $url = '', $data = array()){
		$json = '';
		if($data || IS_AJAX){
			$json['data'] = $data;
		}
		parent::error($info, $url, $json);
	}
	protected function json_success($info = '',$data = '',$status = 200){
		$json['data']   = $data ? $data : null;
		$json['status'] = $status;
		$json['info']   = $info;
		$json = $this->ajaxReturn($json, 'json', JSON_UNESCAPED_UNICODE);
	}
	protected function json_error($info='',$data = '',$status = 400){
		$json['data']   = $data ? $data : null;
		$json['status'] = $status;
		$json['info']   = $info;
		$json = $this->ajaxReturn($json, 'json', JSON_UNESCAPED_UNICODE);
	}
	/**
	 * GET请求处理
	 * @param  string $field         get参数名
	 * @param  string $empty_msg     get值为空，提示信息
	 * @param  string $default_value get值为空，默认值
	 * @param  string $check_type    验证类型，具体参数check模型
	 * @param  string $check_msg     验证失败返回提示信息
	 * @return [type]                返回参数值
	 */
	protected function _get($field,$empty_msg='',$default_value='',$check_type='',$check_msg=''){
		$value = I('get.' . $field);
		$value = $this->common_field_check($value,$empty_msg,$default_value,$check_type,$check_msg);
		$this->assign($field, $value);
		
		return $value;
	}
	/**
	 * POST请求处理
	 * @param  string $field         post参数名
	 * @param  string $empty_msg     post值为空，提示信息
	 * @param  string $default_value post值为空，默认值
	 * @param  string $check_type    验证类型，具体参数check模型
	 * @param  string $check_msg     验证失败返回提示信息
	 * @return [type]                返回参数值
	 */
	protected function _post($field,$empty_msg='',$default_value='',$check_type='',$check_msg=''){
		$value = I('post.' . $field);
		$value = $this->common_field_check($value,$empty_msg,$default_value,$check_type,$check_msg);
		$this->assign($field, $value);

		return $value;
	}
	/**
	 * 通用字段验证
	 * @param  [type] $value         [description]
	 * @param  string $empty_msg     [description]
	 * @param  string $default_value [description]
	 * @param  string $check_type    [description]
	 * @param  string $check_msg     [description]
	 * @return [type]                [description]
	 */
	public function common_field_check($value,$empty_msg='',$default_value='',$check_type='',$check_msg=''){
		if(!$value&&$empty_msg){
			$this->error($empty_msg);
		}
		if(!$value){
			$value = $default_value;
		}
		return $value;
	}
	/**
	 * 设置分页
	 * @param [type] $count 总记录数
	 */
	public function set_page($count, $pagesize = 10){
		//导入分页类
		import("ORG.Util.Page");
		$p = new \Think\Page($count ? $count : 0, $pagesize ? $pagesize : 10);
		$p->setConfig('prev','上一页');
		$p->setConfig('next','下一页');
		$page = router_page($p->show());
		$this->assign('page', $page);

		return $page;
	}
	protected function ajax_page($list = '', $count = 0, $tpl = '', $list_field = 'list'){
		$tpl        = $tpl ? $tpl : ACTION_NAME;
		$list_field = $list_field ? $list_field : 'list';
		$page       = $this->_get('p', '', 1);
		$pagesize   = $this->pagesize ? $this->pagesize : 15;
		$total_page = ceil($count / $pagesize);
		//AJAX分页加载数据处理
		$url   = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], '?') ? '' : "?");
		$parse = parse_url($url);
		if(isset($parse['query'])) {
			parse_str($parse['query'], $params);
			unset($params['p']);
			$url = $parse['path'] . '?' . http_build_query($params);
		}
		$ajax_next_page = $url . '&p=' . ($page + 1);
		if($page >= $total_page){
			$ajax_next_page = '';
		}
		// var_dump($page);
		// var_dump($total_page);
		// var_dump($ajax_next_page);
		$this->assign('ajax_next_page', $ajax_next_page);
		if(IS_AJAX && $page > 1){
			// var_dump($list);exit;
			$this->assign($list_field, $list);
			$data['html'] = $this->fetch($tpl . '_ajax_item');
			$data['page']['cur_page']       = $page;
			$data['page']['total_page']     = $total_page;
			$data['page']['ajax_next_page'] = $ajax_next_page;

			$this->success('获取数据成功！', '', $data);
		}
	}
	protected function page($list = array(), $count, $tpl = '', $list_field = 'list'){
		$tpl        = $tpl ? $tpl : ACTION_NAME;
		$list_field = $list_field ? $list_field : 'list';
		$page       = $this->_get('p', '', 1);
		$pagesize   = $this->pagesize ? $this->pagesize : 10;
		//导入分页类
		import("ORG.Util.Page");
		$p = new \Think\Page($count, $pagesize);
		$p->setConfig('prev','上一页');
		$p->setConfig('next','下一页');
		$page_html = $p->show();
		//分页写入模板
		$this->assign('page', $page_html);
		$this->assign('list', $list);
		if(IS_AJAX){
			// var_dump($list);exit;
			$this->assign($list_field, $list);
			$data['html']      = $this->fetch($tpl . '_ajax_item');
			$data['page_html'] = $page_html;

			$this->success('获取数据成功！', '', $data);
		}
	}
	protected function get_user_menu_top(){
		$list = $this->is_lawyer ? C('LAWYER_MENU_LIST') : C('USER_MENU_LIST');
		foreach ($list as $rs) {
			$rs['is_select'] = $rs['is_select'] ? 1 : $this->is_select_menu($rs['url'], $rs['router_url']);
			if(!$rs['is_select']){
				foreach ($rs['list'] as $row) {
					$rs['is_select'] = $rs['is_select'] ? 1 : $this->is_select_menu($row['url'], $row['router_url']);
					if(!$rs['is_select']){
						foreach ($row['list'] as $rw) {
							$rs['is_select'] = $rs['is_select'] ? 1 : $this->is_select_menu($rw['url'], $rw['router_url']);
							foreach ($rw['filter_list'] as $url) {
								$rs['is_select'] = $rs['is_select'] ? 1 : $this->is_select_menu($url);
							}
						}
						foreach ($row['filter_list'] as $url) {
							$rs['is_select'] = $rs['is_select'] ? 1 : $this->is_select_menu($url);
						}
					}
				}
			}
			if($rs['is_select']){
				$this->left_menu_list = $rs['list'];
			}
			$new_list[] = $rs;
		}
		$this->user_menu_top = $new_list;
		return $new_list;
	}
	protected function get_user_menu_left(){
		if(!$this->left_menu_list){
			$this->get_user_menu_top();
		}
		$list = $this->left_menu_list;
		foreach ($list as $rs) {
			$rs['is_select'] = $this->is_select_menu($rs['url'], $rs['router_url']);
			foreach ($rs['filter_list'] as $url) {
				$rs['is_select'] = $rs['is_select'] ? 1 : $this->is_select_menu($url);
			}
			$row_list = array();
			foreach ($rs['list'] as $row) {
				$row['is_select'] = $this->is_select_menu($row['url'], $row['router_url']);
				foreach ($row['filter_list'] as $url) {
					$row['is_select'] = $row['is_select'] ? 1 : $this->is_select_menu($url);
					$rs['is_select']  = $row['is_select'] ? 1 : $rs['is_select'];
				}
				$rs['is_select'] = $row['is_select'] ? 1 : $rs['is_select'];
				$row_list[] = $row;
			}
			$rs['list'] = $row_list;
			$new_list[] = $rs;
		}
		return $new_list;
	}
	protected function is_select_menu($menu_url, $router_url){
		if(C('URL_CASE_INSENSITIVE')){
			$menu_url = parse_name($menu_url);
		}
		$mod_act1    = str_replace(array('?', '=', '&'), '/', $menu_url);
		$mod_act2    = str_replace(array('?', '=', '&'), '/', $router_url);
		$request_url = $_SERVER['REQUEST_URI'];
		if(strpos($request_url, $mod_act1) !== false ? 1 : 0){
			return true;
		}
		if(strpos($request_url, $mod_act2) !== false ? 1 : 0){
			return true;
		}
		return false;
	}
	//获取用户ID
	protected function user_id($is_login = true){
		$user = D('User')->get_user_info($is_login);

		$this->user            = $user;
		$this->user_id         = $user['user_id'] ? $user['user_id'] : 0;
		$this->user_head_url   = $user['head_url'] ? $user['head_url'] : '';
		$this->user_name       = $user['user_name'] ? $user['user_name'] : '';
		$this->user_realname   = $user['realname'] ? $user['realname'] : '';
		$this->user_mobile     = $user['mobile'] ? $user['mobile'] : '';
		$this->user_email      = $user['email'] ? $user['email'] : '';
		$this->user_nickname   = $user['nickname'] ? $user['nickname'] : '';
		$this->user_service_id = $user['service_id'] ? $user['service_id'] : 0;
		$this->set_password    = $user['set_password'] ? $user['set_password'] : '';
		$this->user_city_id    = $user['city_id'] ? $user['city_id'] : 0;
		$this->is_lawyer       = $user['is_lawyer'] ? $user['is_lawyer'] : 0;
		$this->is_auth_email   = $user['is_auth_email'] ? $user['is_auth_email'] : 0;

		// SaaS Key
		$session_saas_key = session('saas_key');
		$get_saas_key     = $this->_get('saas_key');
		$saas_key         = $session_saas_key ? $session_saas_key : $get_saas_key;
		// var_dump($saas_key);
		if($saas_key && $this->user_id > 0){
			$key_info = explode('|', decode($saas_key));
			$saas_enterprise_id = $key_info[0] ? $key_info[0] : 0;
			$saas_user_id       = $key_info[1] ? $key_info[1] : 0;
			// 更新用户SaaS信息
			if($saas_enterprise_id && $saas_user_id){
				D('User')->change_saas_info($this->user_id, $saas_enterprise_id, $saas_user_id);
			}
			session('saas_key', null);
		}

		$this->assign('user', $user);
		$this->assign('user_id', $this->user_id);
		$this->assign('is_lawyer', $this->is_lawyer);
		$this->assign('user_name', $this->user_name);
		$this->assign('user_score', $this->user_score);
		$this->assign('user_email', $this->user_email);
		$this->assign('user_mobile', $this->user_mobile);
		$this->assign('set_password', $this->set_password);
		$this->assign('user_city_id', $this->user_city_id);
		$this->assign('user_head_url', $this->user_head_url);
		$this->assign('user_nickname', $this->user_nickname);
		$this->assign('user_realname', $this->user_realname);
		$this->assign('is_auth_email', $this->is_auth_email);
		$this->assign('user_service_id', $this->user_service_id);

		return $this->user_id;
	}
	// 判断是否有权限操作
	public function lawyer_is_role(){
		$audit_status_desc = array(
			0 => '审核中',
			1 => '审核通过',
			2 => '审核未通过',
		);
		$audit_status = $this->user['lawyer_info']['audit_status'];
		if($audit_status != 1){
			$this->error('对不起，' . $audit_status_desc[$audit_status] . '，无法操作！');
		}
	}
	/**
     * 获取短信验证码
     */
    public function get_smscode(){
		$mobile  = $this->_get('mobile', '手机号不能为空！');
		$type    = $this->_get('type', '', 'register');
		$imgcode = $this->_get('imgcode', '图片验证码不能为空！');
		$verify  = new \Think\Verify();
		if(!$verify->check($imgcode)){
			$this->error('您输入图片验证码不正确！');
		}
		// $this->success('发送成功，请注意查收！');
        if(D('Sms')->send_smscode($mobile, $type)){
            $this->success('发送成功，请注意查收！');
        }else{
            $this->error(D('Sms')->tips_info);
        }
    }
    // 图片验证码
    public function imgcode(){
		$config['imageW']   = $this->_get('w');
		$config['imageH']   = $this->_get('h');
		$config['length']   = 4;
		$config['useNoise'] = false;
		// $config['useImgBg'] = true;
		// $config['useCurve'] = false;
		$config['fontSize'] = 18;
    	$Verify = new \Think\Verify($config);
		$Verify->entry();
    }
    // 验证图片验证码
    public function check_imgcode(){
    	$imgcode = $this->_get('imgcode', '图片验证码不能为空！');
		$verify  = new \Think\Verify();
		if(!$verify->check($imgcode)){
			$this->error('您输入验证码不正确！');
		}
    }
    /**
	 * 验证字段内容是否存在
	 * @return [type] [description]
	 */
	public function valid_field($model='',$where=''){
		$keyword = $this->_post('param');//验证内容
		$name    = $this->_post('name');//验证字段
		$fileds  = $this->_get('fileds');//验证其它字段
		$value   = $this->_get('value');//验证其它值
		//使用模型
		$model = D($model ? $model : CONTROLLER_NAME);

		$where[$name]       = $keyword;
		$where['is_delete'] = 0;
		if($fileds && $value){
			$fileds = explode(',', $fileds);
			$value  = explode(',', $value);
			foreach ($fileds as $key => $field) {
				$where[$field] = $value[$key];
			}
		}
		// var_dump($where);
		$is_exist = $model->where($where)->find();
		// var_dump($model->getLastSql());

		$data['info']   = $is_exist ? '已存在！' : '可以使用';
		$data['status'] = $is_exist ? 'n' : 'y';
		echo_json($data);
	}

	//获取地区数据
	public function get_area_list(){
		$where['parentid'] = $this->_get('parentid');
		$list = D('Area')->where($where)->order('order_id,id')->select();
		$data['list'] = $list;

		$this->success('获取数据成功！', '', $data);
	}
}